package com.zzw.controller;

import com.zzw.api.EmailService;
import com.zzw.pojo.MyResponse;
import org.apache.dubbo.config.annotation.DubboReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * 验证码controller
 *
 * @Author: zhangzhiwei
 * @Date: 2022/4/7 21:05
 */
@RestController
@RequestMapping("/code")
public class CodeController {

    private static final Logger log = LoggerFactory.getLogger(CodeController.class);

    /*@Autowired
    private EmailFeignClient emailFeignClient;*/

    @DubboReference
    private EmailService emailService;



    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 生成验证码，并发送至邮箱，并将验证码存入redis
     */
    @GetMapping("/create/{email}")
    @CrossOrigin
    public MyResponse<Boolean> createCode(@PathVariable String email){

        MyResponse<Boolean> myResponse = new MyResponse<>();
        try {
            int i = new Random().nextInt(1000000) + 100000;
            emailService.sendEmail(email, String.valueOf(i));
            // 验证码入redis
            stringRedisTemplate.opsForValue().set(email, String.valueOf(i), 60, TimeUnit.SECONDS);
            myResponse.setCode(200);
            myResponse.setMsg("发送验证码成功");
            myResponse.setData(true);
        } catch (Exception e) {
            log.error("发送验证码异常", e);
            myResponse.setCode(500);
            myResponse.setMsg("发送验证码异常");
            myResponse.setData(false);
        }
        return myResponse;
    }

}
